import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getUserimg } from '@/api/user'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  UserInfo: {}
}
const mutations = {
  // 存token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 存用户信息
  setUserInfo(state, user) {
    state.UserInfo = user
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.UserInfo = {}
  },
  // 删除token
  removeToken(state) {
    state.token = null
    removeToken()
  }
}
// 登录
const actions = {
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
  },
  // 获取用户信息
  async getUserInfo(context, state) {
    console.log(9999)
    const res = await getUserInfo()
    console.log(res.userId)
    const ress = await getUserimg(res.userId)
    console.log(ress)
    context.commit('setUserInfo', { ...res, ...ress })
    return res
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
